<template>
  <el-card>
    <template #header>
      <div class="u619_div">
        <span>教师管理 </span>
      </div>
    </template>
    <el-card class="!border-none" shadow="never">
      <el-form
        ref="formRef"
        class="mb-[-16px]"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item>
          <el-input
            class="w-[300px]"
            v-model="queryParams.real_name"
            placeholder="教师名称"
            clearable
            @keyup.enter="resetPage"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-cascader
            v-model="queryParams.college"
            class="w-[300px]"
            @change="collegeChange"
            :options="data"
            placeholder="院系/班级"
          ></el-cascader>
        </el-form-item>

        <el-form-item>
          <el-date-picker
            v-model="queryParams.value2"
            start-placeholder="选择开始时间"
            end-placeholder="选择结束时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            class="w-[300px]"
            placeholder="以创建时间范围筛选"
            @change="dateChange"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="resetPage">
            <div>
              <span class="search_btn_icon"> </span>
              查询
            </div>
          </el-button>
          <el-button @click="resetParams">
            <div>
              <span class="reset_btn"></span>
              重置
            </div>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never">
      <el-button type="primary" @click="addUser">
        <div id="u697">
          <span></span>
          添加教师
        </div>
      </el-button>

      <!-- <el-button>
        <div id="u697">
          <span></span>
          批量导入
        </div>
      </el-button> -->
      <el-table
        stripe
        class="mt-2"
        size="large"
        v-loading="pager.loading"
        :data="pager.lists"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column
          label="教师ID"
          prop="id"
          min-width="120"
        ></el-table-column>
        <el-table-column
          label="教师名称"
          prop="real_name"
          min-width="100"
        ></el-table-column>
        <el-table-column label="所属院系" prop="nickname" min-width="120">
          <template #default="{ row }">
            <el-space wrap>
              <el-tag
                v-for="(item, index) in row.classes"
                :key="index"
                type="primary"
                size="mini"
                >{{ item?.college?.name }}</el-tag
              >
            </el-space>
          </template>
        </el-table-column>
        <el-table-column label="所属班级" prop="classesname" min-width="120">
          <template #default="{ row }">
            <el-space wrap>
              <el-tag
                v-for="(item, index) in row.classes"
                :key="index"
                type="primary"
                size="mini"
                >{{ item?.name }}</el-tag
              >
            </el-space>
          </template>
        </el-table-column>
        <el-table-column label="班级学生（人）" prop="classes" min-width="140">
          <template #default="{ row }">
            {{ studentNum(row.classes) }}
          </template>
        </el-table-column>
        <el-table-column
          label="学生作品（个）"
          prop="inviter_name"
          min-width="140"
        >
          <template #default="{ row }">
            {{ workNum(row.classes) }}
          </template>
        </el-table-column>
        <el-table-column label="账号状态" min-width="160">
          <template #default="{ row }">
            <span style="color: #1abc9c" v-if="row.status == 1">• 启用</span>
            <span style="color: #f59a23" v-else>• 停用</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="created_at"
          min-width="180"
        ></el-table-column>

        <el-table-column label="操作" min-width="360" fixed="right">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-button
                class="custom-btn"
                plain
                type="primary"
                @click="gotoDeatil(row)"
              >
                <viewBtnIcon></viewBtnIcon>
              </el-button>
              <el-button
                class="custom-btn"
                plain
                type="primary"
                @click="handleEdit(row)"
              >
                <deiltBtnIcon></deiltBtnIcon>
              </el-button>
              <el-button
                class="custom-btn custom-btn-stop"
                v-if="row.status == 1"
                type="primary"
                @click="BlackList(row)"
              >
                <stopBtnIcon></stopBtnIcon>
              </el-button>
              <el-button
                type="primary"
                class="custom-btn custom-btn-start"
                v-if="row.status == 2"
                @click="BlackList(row)"
              >
                <startBtnIcon></startBtnIcon>
              </el-button>
              <el-button
                class="custom-btn"
                type="danger"
                plain
                @click="handleDelete(row)"
              >
                <delectBtnIcon></delectBtnIcon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <pagination
          v-model="pager"
          @change="getLists"
          background="red"
          layout="prev, pager, next, sizes"
        ></pagination>
      </div>
    </el-card>

    <add-user-pop
      v-if="popShow"
      ref="addUserPopRef"
      @close="popClose"
      @submit="popConfirm"
    ></add-user-pop>
  </el-card>
</template>
<script lang="ts" setup name="consumerLists">
import { usePaging } from "@/hooks/usePaging";
import {
    getTeacherList,
    editTeacher,
    delTeacher,
    getDepartmentList,
} from "@/api/consumer";
import feedback from "@/utils/feedback";
import addUserPop from "./modals/addUserPop.vue";
import { useRequest } from "vue-hooks-plus";

import viewBtnIcon from "@/components/viewBtnIcon/index.vue";
import deiltBtnIcon from "@/components/deiltBtnIcon/index.vue";
import delectBtnIcon from "@/components/delectBtnIcon/index.vue";
import startBtnIcon from "@/components/startBtnIcon/index.vue";
import stopBtnIcon from '@/components/stopBtnIcon/index.vue'

const router = useRouter();

// 获取学院配置
const { data } = useRequest(async () => {
    const _Res = await getDepartmentList({
        page: 1,
        limit: 9999,
    });

    const list: any = [];

    _Res?.data?.forEach((_item) => {
        if (_item?.classes && _item?.classes?.length > 0) {
            list.push({
                value: _item.id,
                label: _item.name,
                children: _item?.classes?.map((_item2) => {
                    return {
                        value: _item2.id,
                        label: _item2.name,
                    };
                }),
            });
        }
    });

    return list;
});

//弹框ref
const addUserPopRef = shallowRef();
const popShow = ref(false);

const queryParams = reactive({
    real_name: "",
    created_start_date: "",
    created_end_date: "",
    college_id: "",
    classes_id: "",
    value2: "",
    college: "",
});

const collegeChange = (_data) => {
    queryParams.college_id = _data?.[0];
    queryParams.classes_id = _data?.[1];
};

const dateChange = (_data) => {
    queryParams.created_start_date = _data?.[0];
    queryParams.created_end_date = _data?.[1];
};

const isSelect = ref<number[]>([]);

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getTeacherList,
    params: queryParams,
});

// 计算学生人数
const studentNum = (_item) => {
    return _item.reduce((acc, cur) => acc + cur.student_num, 0);
};

// 计算作品数
const workNum = (_item) => {
    return _item.reduce((acc, cur) => acc + cur.works_num, 0);
};

//打开创建用户弹框
const addUser = async () => {
    popShow.value = true;
    await nextTick();
    addUserPopRef.value.open();
    //   addUserPopRef.value.setFormData({
    //     nickname: "测试",
    //   });
};

//删除
const handleDelete = async (data: any) => {
    await feedback.prompt(`是否确定删除该教师？`, `操作确认`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
        inputPlaceholder: "请输入备注",
        callback: async ({ action, value }: any) => {
            if (action == "confirm") {
                console.log("确认了");
                try {
                    await delTeacher({ id: data?.id, remark: value });

                    getLists();
                } catch (error) { }
            } else {
            }
        },
        type: "warning",
    });
};

//黑名单
const BlackList = async (data) => {
    await feedback.prompt(
        `是否确定${data?.status == 1 ? "停用" : "启用"}该教师账号？`,
        `操作确认`,
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputType: "textarea",
            inputPlaceholder: "请输入备注",
            callback: async ({ action, value }: any) => {
                if (action == "confirm") {
                    console.log("确认了");
                    try {
                        await editTeacher({
                            ...data,
                            id: data.id,
                            classes_ids: data.classes?.map((e) => e.id)?.join(","),
                            status: data.status === 1 ? 2 : 1,
                            remark: value,
                        });

                        getLists();
                    } catch (error) { }
                } else {
                }
            },
            type: "warning",
        }
    );
};

//多选
const handleSelectionChange = (value: any) => {
    isSelect.value = value.map((item: any) => item.id);
};

//弹框关闭
const popClose = () => {
    popShow.value = false;
};

const popConfirm = () => {
    getLists();
    popShow.value = false;
};

onActivated(() => {
    getLists();
});

getLists();

// 路由跳转
const gotoDeatil = (data: any) => {
    router.push(`/user/teacher/detail?id=${data?.id}`);
};

// 编辑
const handleEdit = async (data: any) => {
    popShow.value = true;
    await nextTick();
    addUserPopRef.value.open();

    const _classes_ids = data.classes.map((item: any) => {
        return [item?.college_id, item?.id];
    });

    addUserPopRef.value.setFormData({
        ...data,
        password_confirm: data.password,
        status: data?.status === 1,
        classes_ids: _classes_ids,
    });
};
</script>

<style lang="scss" scoped></style>
